<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="开始时间" prop="beginTime">
        <el-date-picker clearable v-model="queryParams.beginTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择请假开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择请假结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="请假时长" prop="leaveHour">
        <el-input v-model="queryParams.leaveHour" placeholder="请输入请假时长" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="default" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="default" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="default" @click="handleAdd"
          v-hasPermi="['system:leavetime:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="Download" size="default" @click="handleExport"
          v-hasPermi="['system:leavetime:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leavetimeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请人" align="center" prop="userName" />
      <el-table-column label="请假类别" align="center" prop="leaveType">
        <template #scope="scope">
          <span>{{ scope.row.leaveType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="beginTime" width="180">
        <template #scope="scope">
          <span>{{ parseTime(scope.row.beginTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假时长" align="center" prop="leaveHour" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="ZoomIn" @click="handlePreview(scope.row)">查看进度</el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button> -->
          <!-- <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="请假类型" prop="leaveType">
              <el-select v-model="form.leaveType" placeholder="请选择请假类型" :style="{ width: '220px' }">
                <el-option v-for="(item, index) in leaveTypeOptions" :key="index" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开始时间" prop="beginTime">
              <el-date-picker clearable v-model="form.beginTime" type="date" placeholder="请选择开始时间"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="form.endTime" type="date" placeholder="请选择开始时间"
                value-format="YYYY-MM-DD" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请假时长" prop="leaveHour">
              <el-input-number v-model="form.leaveHour" style="width: 220px;" :min="1" :max="100" placeholder="请输入时长" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请假说明" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请填写请假理由" :maxlength="100" show-word-limit
                :autosize="{ minRows: 4, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import cache from '@/plugins/cache'
import { listLeavetime, addLeavetime } from "@/api/hr/leavetime";
import { processSubmit } from "@/api/workflow/outsideApi";
import { processOperation } from '@/api/workflow/index'
const { proxy } = getCurrentInstance();
const loading = ref(true);
const single = ref(true);       // 非单个禁用
let ids = ref([]);    // 选中数组
// 非多个禁用
let multiple = ref(true);
// 显示搜索条件
let showSearch = ref(true);
// 总条数
let total = ref(0);
// 【请填写功能名称】表格数据
let leavetimeList = ref([]);
// 弹出层标题
let title = ref('');
// 是否显示弹出层
let open = ref(false);
// 查询参数
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  leaveType: null,
  beginTime: null,
  endTime: null
});
// 表单参数
let form = reactive({
  id: null,
  userName: cache.session.get('userName') || null,
  userId: cache.session.get('userId'),
  leaveType: 1,
  beginTime: null,
  endTime: null,
  leaveHour: null,
  remark: null,
});
// 表单校验
let rules = {
  beginTime: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
  endTime: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
  leaveHour: [{ required: true, message: "请假时长不能为空", trigger: "blur" }],
};
const leaveTypeOptions = [{
  "label": "年假",
  "value": 1
}, {
  "label": "事假",
  "value": 2
}, {
  "label": "婚假",
  "value": 3
}, {
  "label": "病假",
  "value": 4
}];
let startForm = reactive({
  formCode: "RUYILEAVE",//流程设计的流程类型
  isLowCodeFlow: true,//低代码表单标识
  lfFields: form,//表单字段json
  operationType: 1,//1固常量:代表流程发起
  userId: cache.session.get('userId') || '1',//uaserid发起人id 
});

/** 查询【请填写功能名称】列表 */
function getList() {
  loading.value = true;
  listLeavetime(queryParams).then(response => {
    leavetimeList.value = response.rows.map(item => {
      item.leaveType = getLeaveType(item.leaveType);
      return item;
    });
    total.value = response.total;
    loading.value = false;
  });
}
getList();

/**
 * 获取请假类型名称
 * @param key 
 */
function getLeaveType(key) {
  return leaveTypeOptions.find(c => c.value == key)?.label;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}
// 表单重置
function reset() {
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加请假记录";
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在提交数据，请稍等...");
      form.userName = cache.session.get('userName');
      form.userId = cache.session.get('userId');
      startForm.lfFields = form;
      Promise.all([addLeavetime(form), processOperation(startForm)]).then((res) => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      }).catch(() => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgError("流程发起失败");
        open.value = false;
      });
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('hr/leavetime/export', {
    ...queryParams
  }, `leavetime_${new Date().getTime()}.xlsx`)
}

const handlePreview = (row) => {
  const obj = { path: "/flowTask/mytask" };
  proxy.$tab.closeOpenPage(obj);
}
</script>